package com.ocom.ugcapi.controller;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.ocom.common.constant.WxServiceUrl;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.ugcapi.GzhUserInfo;
import com.ocom.redis.util.RedisUtil;
import com.ocom.ugcapi.client.MinioClientService;
import com.ocom.ugcapi.config.RsaConfig;
import com.ocom.ugcapi.util.RSAHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * @Description: TODO
 * @Author: 朱晖
 * @Date: 2023/4/28
 **/
@Slf4j
@RestController
public class FileUploadController {

	@Resource
	private RedisUtil redisUtil;

	@Autowired
	MinioClientService minioClientService;

	//修改头像
	@PostMapping(WxServiceUrl.URL_fileUpload)
	public Result fileUpload(MultipartFile file, String token){
		// 解析token
		GzhUserInfo userInfo = null;
		Gson gson = new Gson();
		try {
			String userStr  = RSAHelper.decipher(token, RsaConfig.privateKey);
			if(userStr == null){
				log.info("Pay-token异常 100 【{}】 ", token);
				return ResultUtil.error(ResultEnum.Err_3042);
			}
			userInfo = gson.fromJson(userStr,GzhUserInfo.class);
		} catch (Exception e) {
			log.info("Pay-token异常 2 【{}】 ", e);
			return ResultUtil.error(ResultEnum.Err_3042);
		}

		Object tokenRedis = redisUtil.get("gzhToken:" + userInfo.getComId()+":"+userInfo.getPId());
		if (tokenRedis == null) {
			return ResultUtil.error(ResultEnum.Err_4028);
		}

		//判断随机数是否一致
		GzhUserInfo userInfo1 = JSON.parseObject((String) tokenRedis,GzhUserInfo.class);
		if(!userInfo1.getLoginSecret().equals(userInfo.getLoginSecret())){
			return ResultUtil.error(ResultEnum.Err_4028);
		}
		if(file==null){
			return ResultUtil.error(ResultEnum.Err_3057);
		}
		return   minioClientService.upload(file);


	}
}
